function urlParameterValue( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

$(document).ready(function() {
   var $calendar = $('#calendar');
   var id = 10;

   $calendar.weekCalendar({
      displayOddEven: true,
      readonly: true,
      timeslotsPerHour : 2,
      buttons: false,      
      allowCalEventOverlap : true,
      overlapEventsSeparate: true,
      firstDayOfWeek : 1,
      businessHours :{start: 8, end: 21, limitDisplay: true },
      daysToShow : 5,
      switchDisplay: {},
      getHeaderDate: function(date, calendar) {
			return $(calendar).weekCalendar('option', 'longDays')[date.getDay()];
      },
      title: function(daysToShow) {
			return "";
      },
      height : function($calendar) {
         return $(window).height() - $("h1").outerHeight() - 100;
      },
      eventRender : function(calEvent, $event) {
		/*
         if (calEvent.end.getTime() < new Date().getTime()) {
            $event.css("backgroundColor", "#aaa");
            $event.find(".wc-time").css({
               "backgroundColor" : "#999",
               "border" : "1px solid #888"
            });
         }
		*/
      },
      draggable : function(calEvent, $event) {
         return calEvent.readOnly != true;
      },
      resizable : function(calEvent, $event) {
         return calEvent.readOnly != true;
      },
      eventNew : function(calEvent, $event) {

      },
      eventDrop : function(calEvent, $event) {
        
      },
      eventResize : function(calEvent, $event) {
      },
      eventClick : function(calEvent, $event) {
         var $dialogContent = $("#event_edit_container");
         resetForm($dialogContent);

         $dialogContent.dialog({
            modal: true,
            title: calEvent.title,
            width: 420,
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },
            buttons: {
            }
         }).show();

         var startField = $dialogContent.find("span[id='start']");
         var endField = $dialogContent.find("span[id='end']");
         var rmpField = $dialogContent.find("span[id='rmpScore']");
         var myumField = $dialogContent.find("span[id='myumScore']");
         var weightedField = $dialogContent.find("span[id='weightedScore']");
         var professorField = $dialogContent.find("span[id='professor']");         
         
         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         
         startField.html($calendar.weekCalendar("formatTime", calEvent.start));
         endField.html($calendar.weekCalendar("formatTime", calEvent.end));
         if(calEvent.professor)
            professorField.text(calEvent.professor);
        else
            professorField.text("n/a");
         
         if(calEvent.rmpScore)
            rmpField.text(calEvent.rmpScore.toFixed(2));
        else
            rmpField.text("n/a");
            
         if(calEvent.myumScore)
            myumField.text(calEvent.myumScore.toFixed(2));
        else
            myumField.text("n/a");
        
         if(calEvent.weightedScore)
            weightedField.text(calEvent.weightedScore.toFixed(2).toString() + "%");
        else
            weightedField.text("n/a");
         
         $(window).resize().resize(); //fixes a bug in modal overlay size ??
      },
      eventMouseover : function(calEvent, $event) {
      },
      eventMouseout : function(calEvent, $event) {
      },
      noEvents : function() {
      },
      
      data: "/get_schedule",
      jsonOptions : function(element) {
          return {'schedule': urlParameterValue("schedule")};
      }
   });

   function resetForm($dialogContent) {
      $dialogContent.find("input").val("");
      $dialogContent.find("textarea").val("");
   }

   var $endTimeField = $("select[name='end']");
   var $endTimeOptions = $endTimeField.find("option");
   var $timestampsOfOptions = {start:[],end:[]};

   //reduces the end time options to be only after the start time options.
   $("select[name='start']").change(function() {
      var startTime = $timestampsOfOptions.start[$(this).find(":selected").text()];
      var currentEndTime = $endTimeField.find("option:selected").val();
      $endTimeField.html(
            $endTimeOptions.filter(function() {
               return startTime < $timestampsOfOptions.end[$(this).text()];
            })
            );

      var endTimeSelected = false;
      $endTimeField.find("option").each(function() {
         if ($(this).val() === currentEndTime) {
            $(this).attr("selected", "selected");
            endTimeSelected = true;
            return false;
         }
      });

      if (!endTimeSelected) {
         //automatically select an end date 2 slots away.
         $endTimeField.find("option:eq(1)").attr("selected", "selected");
      }

   });


   var $about = $("#about");

   $("#about_button").click(function() {
      $about.dialog({
         title: "About this calendar demo",
         width: 600,
         close: function() {
            $about.dialog("destroy");
            $about.hide();
         },
         buttons: {
            close : function() {
               $about.dialog("close");
            }
         }
      }).show();
   });


});
